<?php

require "EJPDBConfig.php";

$ejConn;

function EJConnectDB() {
    global $ejConn;
    global $ejServer;
    global $ejUsername;
    global $ejPassword;
    global $ejDBName;

    $server = $ejServer;
    $username = $ejUsername;
    $password = $ejPassword;
    $dbname = $ejDBName;

    if ($ejConn) {
        return true;
    }
    
    $ejConn = new mysqli($server, $username, $password, $dbname);
    if ($ejConn->connect_error) {
        W3LogFatal($ejConn->connect_error);
        return false;
    }

    return true;
}

function EJCloseDB() {
    global $ejConn;

    if ($ejConn) {
        $ejConn->close();
    }
}

function EJExecuteSQL($sql) {
    global $ejConn;

    if (!EJConnectDB()) {
        return false;
    }

    if (!$ejConn->query($sql)) {
        return false;
    }

    return true;
}

function EJReadTable($sql, $callback) {
    global $ejConn;

    if (!EJConnectDB()) {
        W3LogWarning("No DB connection when read table");
        return false;
    }

    $result = $ejConn->query($sql);
    if ($result->num_rows > 0) {
        for ($row = 0; $row < $result->num_rows; $row++) {
            $result->data_seek($row);
            $rowData = $result->fetch_assoc();
            $callback($rowData);
        }
    }

    return true;
}

function EJReadSingleResultFromTable($aid, $sql) {
    return EJReadResultFromTable($aid, $sql, false);
}

function EJReadMultiResultFromTable($aid, $sql) {
    return EJReadResultFromTable($aid, $sql, true);
}

function EJReadResultFromTable($aid, $sql, $isResultArray) {
    $result = "{" . W3CreateSuccessfulPartialResult() . "," . W3MakeString(w3ApiResultData) . ($isResultArray ? ":[" : ":{");
    EJReadTable($sql, function ($row) use (&$result, $aid, $isResultArray) {
        $apiDef = W3GetAPIDef($aid);
        $columns = $apiDef[w3ApiResult][w3ApiResultData];
        if ($isResultArray) {
            $result .= "{";
        }
        foreach ($columns as $value) {
            $resultForColumn = $row[$value[w3ApiDataValue]];
            $result .= W3MakeString($value[w3ApiDataValue]) . ":" . W3MakeString($resultForColumn) . ",";
        }
        if ($isResultArray) {
            $result = rtrim($result, ",") . "},";
        }
    });
    $result = rtrim($result, ",") . ($isResultArray ? "]}" : "}}");

    return $result;
}

 ?>
